package com.fipl.taksar;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

	private Bundle savedInstanceState;
	private Context context;
	private EditText clientEditText;
	private EditText clientpwdEditText;
	private Button loginButton,resetButton;
	private String host;
	private String clientName;
	//Propiedad que describe si el usuario esta autenticado correctamente
	private String dbname;
	private String clientPwd;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		this.savedInstanceState=savedInstanceState;
		setContentView(R.layout.login);
		context = getApplicationContext();
		
		
		Log.d("System out", "bool val "+((GlobalData)this.getApplicationContext()).isLoginFlag());
		
		//materializando los elementos xml en objetos
			clientEditText = (EditText)findViewById(R.id.userNameEditText);
			//clientEditText.setText("TKRadmin");
			clientpwdEditText = (EditText)findViewById(R.id.passwordEditText);
			//clientpwdEditText.setText("defaultpass");
			loginButton = (Button)findViewById(R.id.login_button);
			resetButton = (Button)findViewById(R.id.reset_button);
		//estableciendo parámetros de conexión
		this.host = "megan.teksar.com.mx";	
			
			setListeners();
	}

	/*
	 * Método encargado de establecer los listeners para los widgets que lo requieran en esta
	 * Activity
	 */
	private void setListeners(){
		
		loginButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				//variable que almacenará la respuesta JSON del servidor
				StringBuffer jsontext = new StringBuffer();
				// TODO Auto-generated method stub
				clientName = clientEditText.getText().toString();
				clientPwd = clientpwdEditText.getText().toString();

				//url de autenticación
//				String urlStr = "http://megan.teksar.com.mx/jsonlogin.php?username="+clientName+"&password="+clientPwd;
				String urlStr = "http://"+host+"/DBXTra/index.php/welcome/validaLoginAndroid/"+clientName+"/"+clientPwd;
				try{
					URL url = new URL(urlStr);
					HttpURLConnection connection =  (HttpURLConnection)url.openConnection();
					BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
					String data="";
					//recolección de la información obtenida 
					while((data = br.readLine())!=null){
							jsontext.append(data);
					}
					setData(jsontext);
					redirect();

				}catch (Exception e) {
					// TODO: handle exception
					Toast.makeText(getApplicationContext(), "Error: "+e.getMessage(), Toast.LENGTH_SHORT).show();
				}

			}
		});
		
		resetButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				clientEditText.setText("");
				clientpwdEditText.setText("");
			}
		});
		
	}
	
	public void setData(StringBuffer jsontext){
		try{
			JSONObject json = new JSONObject(jsontext.toString());
			
				boolean valid = json.getBoolean("valid");
				//si es válida la autenticación, entonces el objeto JSON tiene más parámetros
				// para un login válido - {"valid" : true,"dbname" : Stringvalue,"username":Stringvalue}
				// para un login fallido - {"valid" : false}
				if(valid){
					dbname = json.getString("dbname");
					clientName = json.getString("username");
				}
			
			
			((GlobalData)this.getApplicationContext()).setLoginFlag(valid);
			((GlobalData)this.getApplicationContext()).setDbName(dbname);
			((GlobalData)this.getApplicationContext()).setClientName(clientName);
			
			Log.d("System out", "bool val "+((GlobalData)this.getApplicationContext()).isLoginFlag());
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.d("System out", "Error "+clientName+e.getMessage());
		}
		
	}
	
	private void redirect(){
		
		if( ((GlobalData)this.getApplicationContext()).isLoginFlag() ){
			//SelectNotification();
			Toast.makeText(this, "login success!!",Toast.LENGTH_SHORT).show();
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(),
					ConfigurationActivity.class);
			startActivity(intent);
		}else{
			//se invita a autenticarse de nuevo
			Toast.makeText(this, "login failed!!",Toast.LENGTH_SHORT).show();
		}
	}
	
}
